#include "../../include/service/feature_sqm.h"
#include "../../include/model/model_dir.h"
#include "../../include/our_header.h"
#include <mysql/mysql_com.h>
#include <my_header.h>

// 通过用户名查last_dir_id获取当前工作目录，然后通过last_dir_id在Dir表中查path，再拼上
//
int makeDir(MYSQL *conn,int cur_dir_id,char dirname[],int *dir_id){
    DIR_M parent_dir = {0};
    DIR_M new_dir = {0};
    // 查找父目录的path,作为新path拼接的前缀
    selectDirByid(conn,cur_dir_id,&parent_dir);
    
    // 进行拼接
    char new_path[255] = "";
    strcpy(new_path,parent_dir.path);
    sprintf(new_path,"%s/%s",new_path,dirname);

    // 为new_dir赋值
    new_dir.user_id = parent_dir.user_id;
    new_dir.file_id = -1;
    strcpy(new_dir.file_name,dirname);
    new_dir.parent_id = parent_dir.id;
    strcpy(new_dir.type,"d");
    strcpy(new_dir.path,new_path);
    
    insertDir(conn,&new_dir,dir_id);

    return 0;
}

//int removeDir(MYSQL *conn,int cur_dir_id,char dirname[]){
//    DIR_M dir = {0};
//    dir.id = cur_dir_id;
//    strcpy(dir.file_name,dirname);
//    deleteDir(conn,&dir);
//    return 0;
//
//}
int removeDir(MYSQL *conn, int parent_dir_id, char dirname[]) {
    DIR_M parent_dir = {0};
    DIR_M target_dir = {0};
    int target_id = 0;
    char target_path[255] = {0};

    // 1. 获取父目录信息（需实现 selectDirByid）
    if (selectDirByid(conn, parent_dir_id, &parent_dir) != 0) {
        fprintf(stderr, "Error: Parent directory (ID=%d) not found.\n", parent_dir_id);
        return -1;
    }

    // 2. 拼接目标目录路径并检查是否存在
    sprintf(target_path, "%s/%s", parent_dir.path, dirname);
    if (getDir_idByPid_Path(conn, parent_dir.user_id, target_path, &target_id) != 0 || target_id == 0) {
        fprintf(stderr, "Error: Directory '%s' not found under parent ID=%d.\n", dirname, parent_dir_id);
        return -1;
    }

    // 3. 填充目标目录信息（仅需 id 和 file_name）
    target_dir.id = target_id;
    strcpy(target_dir.file_name, dirname);

    // 4. 调用 deleteDir 删除
    if (deleteDir(conn, &target_dir) != 0) {
        fprintf(stderr, "Error: Failed to delete directory (ID=%d).\n", target_id);
        return -1;
    }

    printf("Deleted directory: %s (ID=%d)\n", dirname, target_id);
    return 0;
}
